# https://help.aliyun.com/document_detail/130636.htm?spm=a2c4g.128282.0.0.4a715d7a4xRckW#t1359228.html
# pip install alibabacloud_dcdn20180115==1.1.6

import sys, os
import time
import json

from typing import List

from alibabacloud_dcdn20180115.client import Client as dcdn20180115Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dcdn20180115 import models as dcdn_20180115_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class AliyunDCDN:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> dcdn20180115Client:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 必填，您的 AccessKey ID,
            access_key_id=access_key_id,
            # 必填，您的 AccessKey Secret,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = f'dcdn.aliyuncs.com'
        return dcdn20180115Client(config)

    @staticmethod
    def main(
        push_objects
    ) -> None:
        # 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html
        client = AliyunDCDN.create_client('LTAI5t7TipZippvqYna4QAgp', 'b7VuMx1pE9jEUfNEGuGnQNNmUFuLc3')
        preload_dcdn_object_caches_request = dcdn_20180115_models.PreloadDcdnObjectCachesRequest(
            area='overseas',
            l_2preload=True,
            object_path=push_objects
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            resp = client.preload_dcdn_object_caches_with_options(preload_dcdn_object_caches_request, runtime)
            print(resp)
        except Exception as error:
            # 如有需要，请打印 error
            print(UtilClient.assert_as_string(error.message))

def push(cdnurls):
    aliyunCDN = AliyunDCDN()

    push_count = 30
    count = int(len(cdnurls)/push_count) + 1
    for i in range(count):
        step = cdnurls[i * push_count:i * push_count + push_count]

        pushobjects = "\n".join(step)
        print("push urls: \n" + pushobjects)
        aliyunCDN.main(pushobjects)

        time.sleep(1)
    print("push cdn finished")

if __name__ == '__main__':
    with open(os.path.join(os.getcwd(), "cdnurls.json"), "r") as freader:
        data = freader.readlines()
        push(data)